<template>
  <div class="component-live-add-or-update mod-live-room-add-or-update">
    <div class="new-page-title">
      <div class="line" />
      <div class="text">
        {{
          !dataForm.roomId ? $t('live.addNewLiveRoom') : $t('live.viewLRoomInfo')
        }}
      </div>
    </div>
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="120px"
      @submit.prevent
      @keyup.enter="dataFormSubmit()"
    >
      <el-form-item
        :label="$t('live.liveName')"
        prop="name"
      >
        <el-input
          v-model.trim="dataForm.name "
          :disabled="dataForm.liveStatus !== 0"
          maxlength="17"
          style="width: 500px;"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('live.anchorName')"
        prop="nickName"
      >
        <el-input
          v-model="dataForm.nickName"
          maxlength="15"
          :disabled="dataForm.liveStatus !== 0 && dataForm.liveStatus !== 3"
          style="width: 500px;"
          show-word-limit
        />
        <p class="live-tips">
          {{ $t("live.liveTip1") }}
        </p>
      </el-form-item>
      <el-form-item
        :label="$t('live.anchorMobile')"
        prop="userMobile"
      >
        <el-input
          v-model="dataForm.userMobile"
          :maxlength="11"
          style="width: 500px;"
          show-word-limit
          :disabled="dataForm.liveStatus !== 0 && dataForm.liveStatus !== 3"
        />
      </el-form-item>
      <el-form-item
        :label="$t('live.liveTime')"
        class="liveTime"
      >
        <div class="live-time-row">
          <el-form-item prop="startTime">
            <el-date-picker
              v-model="dataForm.startTime"
              :disabled="dataForm.liveStatus !== 0 || isDisabledDate"
              type="date"
              :placeholder="$t('live.chooseStartDate')"
              :disabled-date="disabledDate"
              value-format="YYYY-MM-DD"
              style="width:144px"
            />
            <el-time-select
              v-model="startTimeValue"
              start="00:00"
              step="00:30"
              end="23:30"
              style="width:125px"
              :disabled="dataForm.liveStatus !== 0 || isDisabledDate"
              :placeholder="$t('text.startTime')"
              @change="onVerifyField('startTime')"
            />
          </el-form-item>
          <div class="tip">
            {{ $t("date.tip") }}
          </div>
          <el-form-item prop="endTime">
            <el-date-picker
              v-model="dataForm.endTime"
              :disabled="dataForm.liveStatus !== 0 || isDisabledDate"
              type="date"
              :placeholder="$t('live.chooseEndDate')"
              :disabled-date="disabledDate"
              value-format="YYYY-MM-DD"
              style="width:144px"
            />
            <el-time-select
              v-model="endTimeValue"
              start="00:00"
              step="00:30"
              end="23:30"
              style="width:125px"
              :disabled="dataForm.liveStatus !== 0 || isDisabledDate"
              :placeholder="$t('text.endTime')"
              @change="onVerifyField('endTime')"
            />
          </el-form-item>
          <br>
        </div>
        <p class="live-tips">
          {{ $t("live.liveTimeTip") }}
        </p>
      </el-form-item>
      <el-form-item
        :label="$t('live.liveBackgroundImage')"
        prop="coverImg"
      >
        <img-upload
          v-model="dataForm.coverImg"
          :disabled="dataForm.liveStatus !== 0"
          @update:model-value="()=>onVerifyField('coverImg')"
        />
        <p class="live-tips">
          {{ $t("live.recommendedSize") }}：1080{{ $t("live.pixel") }} * 1920{{ $t("live.pixel") }}
        </p>
      </el-form-item>
      <!-- <el-form-item
        :label="$t('live.anchorSharingPicture')"
        prop="shareImg"
      >
        <img-upload
          v-model="dataForm.shareImg"
          :disabled="dataForm.liveStatus !== 0"
        />
        <p class="live-tips">
          {{ $t("live.recommendedSize") }}：800{{ $t("live.pixel") }} * 640{{ $t("live.pixel") }}
        </p>
      </el-form-item> -->
      <el-form-item
        :label="$t('live.liveCoverImage')"
        prop="feedsImg"
      >
        <img-upload
          v-model="dataForm.feedsImg"
          :disabled="dataForm.liveStatus !== 0"
          @update:model-value="()=>onVerifyField('feedsImg')"
        />
        <p class="live-tips">
          {{ $t("live.recommendedSize") }}：{{ $t("live.recomImaSizeIs") }} 800{{ $t("live.pixel") }} * 800{{ $t("live.pixel") }}
        </p>
      </el-form-item>
      <el-form-item
        :label="$t('live.prod')+':'"
        required
      >
        <div class="prod-card">
          <div
            v-for="(liveProd, index) in liveRoomProdList"
            :key="index"
          >
            <el-card
              :body-style="{ padding: '0px' }"
              style="height: 160px; width: 120px; margin-bottom: 15px;margin-right: 10px;"
            >
              <img-show
                height="104px"
                :src="liveProd.pic"
              />
              <div class="card-prod-bottom">
                <span class="card-prod-name">{{ liveProd.prodName }}</span>
                <el-button
                  type="text"
                  :disabled="dataForm.liveStatus !== 0"
                  class="card-prod-name-buttons"
                  @click="deleteSelectProd(index)"
                >
                  {{ $t("text.delBtn") }}
                </el-button>
              </div>
            </el-card>
          </div>
        </div>
        <div
          v-if="dataForm.liveStatus === 0"
          :class="[dataForm.liveStatus !== 0 ? 'disabled-btn':'','default-btn']"
          @click="addProd()"
        >
          {{ $t("product.select") }}
        </div>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn"
          @click="back()"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          v-if="dataForm.liveStatus === 0"
          class="default-btn primary-btn"
          @click="dataFormSubmit()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </el-form-item>
    </el-form>
    <!-- 商品选择弹窗-->
    <prods-select
      v-if="prodsSelectVisible"
      ref="prodsSelectRef"
      @refresh-select-prods="selectIndexProd"
    />
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import ImgUpload from '@/components/img-upload/index.vue'
import ProdsSelect from '@/components/prods-select/index.vue'
import { isMobile, isStarMobile } from '@/utils/validate'
import { getDateTimeRange, getParseTime } from '@/utils/datetime'

// eslint-disable-next-line no-unused-vars
const validateMobile = (rule, value, callback) => {
  if (dataForm.roomId ? !isStarMobile(value) : !isMobile(value)) {
    callback(new Error($t('sys.mobilePhoneError')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validatorDateRange = (rule, value, callback) => {
  if (rule.field === 'startTime' && (!startTimeValue.value || !dataForm.startTime)) {
    callback(new Error($t('publics.noNull')))
  }
  if (rule.field === 'endTime' && (!endTimeValue.value || !dataForm.endTime)) {
    callback(new Error($t('publics.noNull')))
  }
  if (dataForm.liveStatus === 3 || isDisabledDate.value) {
    callback()
  }
  const startTime = dataForm.startTime + ' ' + startTimeValue.value + ':00'
  const endTime = dataForm.endTime + ' ' + endTimeValue.value + ':00'
  if (rule.field === 'startTime' && new Date() > Date.parse(startTime)) {
    callback(new Error($t('groups.startTime')))
  }
  if (rule.field === 'startTime' && Date.parse(startTime) >= Date.parse(endTime)) {
    callback(new Error($t('marketing.timeCanThanOrEqualTo')))
  }
  if (rule.field === 'endTime' && Date.parse(startTime) >= Date.parse(endTime)) {
    callback(new Error($t('marketing.timeCanThanOrEqualTo2')))
  }
  if (rule.field === 'endTime' && new Date() > Date.parse(endTime)) {
    callback(new Error($t('groups.endTime')))
  }
  callback()
}

const dataRule = reactive(
  {
    name: [
      { required: true, message: $t('live.liveRoomNameCannotBeEmpty'), trigger: 'blur' }
    ],
    nickName: [
      { required: true, message: $t('live.anchoBeEmp'), trigger: 'blur' }
    ],
    userMobile: [
      { required: true, message: $t('sys.mobilePhoneNoNull'), trigger: 'blur' },
      { validator: validateMobile, trigger: 'blur' }
    ],
    coverImg: [
      { required: true, message: $t('live.backEmpty'), trigger: 'blur' }
    ],
    shareImg: [
      { required: true, message: $t('live.hostSnPict'), trigger: 'blur' }
    ],
    feedsImg: [
      { required: true, message: $t('live.liveEmpty'), trigger: 'blur' }
    ],
    startTime: [
      { required: true, message: $t('publics.noNull'), trigger: 'blur' },
      { required: true, validator: validatorDateRange, trigger: 'blur' }
    ],
    endTime: [
      { required: true, message: $t('publics.noNull'), trigger: 'blur' },
      { required: true, validator: validatorDateRange, trigger: 'blur' }
    ]
  }
)

// 验证单个字段
const onVerifyField = (attr) => {
  dataFormRef.value?.validateField(attr)
}

const disabledDate = (time) => {
  return time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
}

const prodsSelectVisible = ref(false)
const isSubmit = ref(false)
const liveRoomProdList = ref([])
const dataFormRef = ref(null)
const dataForm = reactive({
  roomId: null,
  name: null,
  nickName: null,
  userMobile: null,
  coverImg: null,
  shareImg: null,
  feedsImg: null,
  liveStatus: null,
  startTime: null,
  endTime: null,
  status: null,
  prodIds: []
})
const startTimeValue = ref('')
const endTimeValue = ref('')

onMounted(() => {
  const flag = sessionStorage.getItem('b2cLiveRoomData') !== 'undefined'
  const data = flag ? JSON.parse(sessionStorage.getItem('b2cLiveRoomData')) : null
  init(data)
  const title = !dataForm.roomId ? $t('live.addNewLiveRoom') : $t('live.viewLRoomInfo')
  useCommonStore().replaceSelectMenu(title)
})

const isDisabledDate = ref(false)
const init = (data) => {
  if (data) {
    dataForm.roomId = data.roomId
    dataForm.name = data.name
    dataForm.nickName = data.nickName
    dataForm.userMobile = data.userMobile
    dataForm.coverImg = data.coverImg
    dataForm.shareImg = data.shareImg
    dataForm.feedsImg = data.feedsImg
    dataForm.liveStatus = data.liveStatus
    dataForm.startTime = data.startTime
    dataForm.endTime = data.endTime
    dataForm.prodIds = data.prodIds
  } else {
    dataForm.liveStatus = 0
  }
  isSubmit.value = false
  liveRoomProdList.value = []
  nextTick(() => {
    dataFormRef.value.resetFields()
    const datetimeRange = getDateTimeRange()
    dataForm.startTime = datetimeRange.startTime
    dataForm.endTime = datetimeRange.endTime
    startTimeValue.value = datetimeRange.currentTime
    endTimeValue.value = datetimeRange.currentTime
    if (dataForm.roomId) {
      http({
        url: http.adornUrl('/multishop/live/liveRoom/info/' + dataForm.roomId),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        dataForm.roomId = data.roomId
        dataForm.name = data.name
        dataForm.nickName = data.nickName
        dataForm.userMobile = data.userMobile
        dataForm.coverImg = data.coverImg
        dataForm.shareImg = data.shareImg
        dataForm.feedsImg = data.feedsImg
        dataForm.liveStatus = data.liveStatus
        dataForm.startTime = data.startTime
        dataForm.endTime = data.endTime
        dataForm.prodIds = data.prodIds
        dataForm.status = data.status
        startTimeValue.value = dataForm.startTime ? dataForm.startTime.substring(11, dataForm.startTime.length - 3) : ''
        endTimeValue.value = dataForm.endTime ? dataForm.endTime.substring(11, dataForm.endTime.length - 3) : ''
        dataForm.startTime = getParseTime(dataForm.startTime, '{y}-{m}-{d}')
        dataForm.endTime = getParseTime(dataForm.endTime, '{y}-{m}-{d}')
        // 当前时间超出开始时间时，开始时间不可修改
        tmepStartTime = data.startTime
        if (new Date() > Date.parse(data.startTime)) {
          isDisabledDate.value = true
        } else {
          startTimeCountDown()
        }
      })
      // 获取商品列表
      http({
        url: http.adornUrl('/multishop/live/liveRoom/listLiveRoomProd'),
        method: 'get',
        params: http.adornParams({
          roomId: dataForm.roomId
        })
      }).then(({ data }) => {
        liveRoomProdList.value = data.map(x => x.product)
        if (dataForm.status !== null && dataForm.status === -1) {
          // 用户注销
          ElMessageBox.confirm($t('live.liveAnchorNotExist'))
        } else if (dataForm.status !== null && dataForm.status !== 1) {
          // 用户禁用
          ElMessageBox.confirm($t('live.liveAnchorError'))
        }
      })
    }
  })
}

let liveTimer = null
let tmepStartTime = ''
const startTimeCountDown = () => {
  if (new Date().getTime() < Date.parse(tmepStartTime)) {
    liveTimer = setTimeout(startTimeCountDown, 1000)
  } else {
    isDisabledDate.value = true
    liveTimer && clearTimeout(liveTimer)
  }
}
// 表单提交
const dataFormSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (liveRoomProdList.value.length === 0) {
        ElMessage({
          message: $t('live.liveProdTip'),
          type: 'error',
          duration: 1500
        })
        return
      }
      if (isSubmit.value) {
        return
      }
      dataForm.prodIds = liveRoomProdList.value.map(x => x.prodId)
      const startTime = dataForm.startTime
      const endTime = dataForm.endTime
      dataForm.startTime = dataForm.startTime && startTimeValue.value ? dataForm.startTime + ' ' + startTimeValue.value + ':00' : ''
      dataForm.endTime = dataForm.endTime && endTimeValue.value ? dataForm.endTime + ' ' + endTimeValue.value + ':00' : ''
      isSubmit.value = true
      http({
        url: http.adornUrl('/multishop/live/liveRoom'),
        method: dataForm.roomId ? 'put' : 'post',
        data: http.adornData(dataForm)
      }).then(() => {
        isSubmit.value = true
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            back()
          }
        })
      }).catch(() => {
        isSubmit.value = false
      })
      dataForm.startTime = startTime
      dataForm.endTime = endTime
    }
  })
}
// 添加指定商品
const selectIndexProd = (prods) => {
  prodsSelectVisible.value = false
  if (prods) {
    liveRoomProdList.value = prods
  }
}
const deleteSelectProd = (index) => {
  liveRoomProdList.value.splice(index, 1)
}
// 打开选择商品
const prodsSelectRef = ref(null)
const addProd = () => {
  prodsSelectVisible.value = true
  nextTick(() => {
    prodsSelectRef.value?.init(liveRoomProdList.value)
  })
}
const router = useRouter()
const back = () => {
  router.push({
    path: '/marketing/live/index'
  })
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item__content) {
  display: block;
}
.mod-live-room-add-or-update {
  .live-tips {
    color: #aaa;
    line-height: 20px;
    margin: 0;
    padding: 0;
  }
  .live-time-row {
    display: flex;
    .tip {
      margin: 0 10px;
    }
  }
}

.liveTime :deep(.el-form-item__label:before){
  content: '*';
  color: #F56C6C;
  margin-right: 4px;
}
:deep(.el-date-editor .el-input__suffix>.el-icon-circle-close) {
  display: none
}
:deep(.el-date-editor .el-input__suffix>.el-icon-circle-check) {
  display: none
}
.prod-card {
  display: flex;
  flex-wrap: wrap;
  .card-prod-bottom{
    position: relative;
    text-align: left;
    .card-prod-name{
      margin: auto;
      padding: 0 6px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 118px;
      display: inline-block;
    }
    .card-prod-name-buttons{
      position: absolute;
      top: 24px;
      right: 10px;
      font-size: 12px;
    }
  }
}
.liveTime :deep(.el-form-item__error) {
  top:54px;
}

</style>
